import React, { useState } from 'react';
import { Menu, Typography, Spin, Alert } from 'antd';
import { DownOutlined, RightOutlined, AppstoreOutlined } from '@ant-design/icons';
import { useProduct } from '../context/ProductContext';
import type { MenuProps } from 'antd';

const { Title, Text } = Typography;

const Sidebar: React.FC = () => {
  const { state, setSelectedCategory } = useProduct();
  const { categories, loading, error } = state;
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);

  // 构建菜单项
  const buildMenuItems = (): MenuProps['items'] => {
    return categories.map(category => ({
      key: category.id,
      icon: <AppstoreOutlined />,
      label: category.name,
      children: category.subcategories.map(subcategory => ({
        key: `${category.id}-${subcategory.id}`,
        label: (
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span>{subcategory.name}</span>
            <Text type="secondary" style={{ fontSize: '12px' }}>
              ({subcategory.products.length})
            </Text>
          </div>
        ),
      })),
    }));
  };

  const handleMenuClick: MenuProps['onClick'] = ({ key, keyPath }) => {
    // 如果是子菜单项（keyPath长度为2）
    if (keyPath.length === 2) {
      const [subcategoryKey, categoryKey] = keyPath;
      
      // 子分类的key格式是 "categoryId-subcategoryId"
      // 需要从subcategoryKey中提取真正的subcategoryId
      const keyParts = subcategoryKey.split('-');
      
      if (keyParts.length >= 2) {
        const categoryId = categoryKey;
        // 移除第一部分（categoryId），剩下的就是subcategoryId
        const subcategoryId = keyParts.slice(1).join('-');
        
        // 验证这些ID是否存在
        const category = categories.find(c => c.id === categoryId);
        if (category) {
          const subcategory = category.subcategories.find(s => s.id === subcategoryId);
          
          if (subcategory) {
            setSelectedCategory(categoryId, subcategoryId);
          }
        }
      }
    } else if (keyPath.length === 1) {
      // 点击的是主分类，处理展开/收起逻辑
      setExpandedKeys(prev => 
        prev.includes(key) 
          ? prev.filter(k => k !== key)
          : [...prev, key]
      );
    }
  };

  if (loading) {
    return (
      <div style={{ 
        height: '100vh', 
        backgroundColor: '#f5f5f5',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      }}>
        <Spin size="large" tip="加载产品数据中..." />
      </div>
    );
  }

  if (error) {
    return (
      <div style={{ 
        height: '100vh', 
        backgroundColor: '#f5f5f5',
        padding: '20px'
      }}>
        <Alert
          message="加载失败"
          description={error}
          type="error"
          showIcon
        />
      </div>
    );
  }

  // 如果没有分类数据，显示上传提示
  if (categories.length === 0) {
    return (
      <div style={{ 
        height: '100vh', 
        color: 'white',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        padding: '20px'
      }}>
        <div style={{ textAlign: 'center' }}>
          <Title level={4} style={{ color: 'white', marginBottom: '16px' }}>
            产品类型选择
          </Title>
          <Text style={{ color: '#8c8c8c', fontSize: '14px', display: 'block', marginBottom: '24px' }}>
            暂无产品数据
          </Text>
          <div style={{ 
            padding: '20px', 
            backgroundColor: '#1f1f1f', 
            borderRadius: '8px',
            marginBottom: '20px'
          }}>
            <Text style={{ color: '#fff', fontSize: '16px', display: 'block', marginBottom: '12px' }}>
              📤 上传Excel文件
            </Text>
            <Text style={{ color: '#8c8c8c', fontSize: '12px', lineHeight: '1.5' }}>
              点击右下角的上传按钮来导入您的产品数据Excel文件
            </Text>
          </div>
          <Text style={{ color: '#666', fontSize: '11px' }}>
            Excel格式：第一行为参数名，第一列为产品名
          </Text>
        </div>
      </div>
    );
  }

  return (
    <div style={{ 
      height: '100vh', 
      color: 'white',
      display: 'flex',
      flexDirection: 'column'
    }}>
      {/* 头部标题 */}
      <div style={{ 
        padding: '20px 16px', 
        borderBottom: '1px solid #303030' 
      }}>
        <Title level={4} style={{ color: 'white', margin: 0 }}>
          产品类型选择
        </Title>
        <Text style={{ color: '#8c8c8c', fontSize: '12px' }}>
          选择您要比较的产品类型
        </Text>
      </div>

      {/* 菜单 */}
      <div style={{ flex: 1, overflow: 'hidden' }}>
        <Menu
          mode="inline"
          theme="dark"
          style={{ 
            backgroundColor: 'transparent',
            border: 'none',
            height: '100%',
            overflowY: 'auto'
          }}
          items={buildMenuItems()}
          onClick={handleMenuClick}
          openKeys={expandedKeys}
          onOpenChange={setExpandedKeys}
          expandIcon={({ isOpen }) => 
            isOpen ? <DownOutlined /> : <RightOutlined />
          }
        />
      </div>

      {/* 底部统计信息 */}
      <div style={{ 
        padding: '16px',
        borderTop: '1px solid #303030'
      }}>
        <Text style={{ color: '#8c8c8c', fontSize: '12px' }}>
          共 {categories.length} 个产品类别
        </Text>
      </div>
    </div>
  );
};

export default Sidebar; 